﻿var _dwToolVer = "2.0.0.5";
var _dwRequiredVer = "2.0.0.5";
var _dwToolExe = "%tool%export12\\export12.exe";
var _dwToolName = "数据窗口工具程序";
/*数据窗口导出excel文件[移植于PB的f_dw2excel相关函数]
	dwId：
		数据窗口id
	flag：
		导出方式(性能说明：导出效果最好的是0，适合小数据量复杂报表，导出效果和速度最均衡的是4，适合大数据量复杂格式的导出)
		 0：小数据量复杂报表，超过1000行的程序会报错返回。导出速度慢，导出效果最好。
		 1:使用saveasascill，如果txtcols存在则动态修改列的类型(客户端必须安装excel)。导出速度快(如果存在txtcols会很慢)，导出效果中等。
		 2:使用saveas(列标题必须是列名＋_t)。导出速度快，导出效果差。
		 3:使用html格式导出。导出速度快，导出效果差。
		 4:大数据量复杂报表，5000行需要5秒，导出速度快，导出效果好。
	title：
		文件名（可以使用路径，比如c:\export\导出文件测试；也可以传入简单文件名，比如导出文件测试；也可以传入空字符串)
	txtcols:
		强制转换为文本列，多列逗号分隔（比如身份证、卡号、保险号等 insr_code,acc_no,idcard）
		此字段只有类型1才有效，保留使用，数据量大会很慢，建议使用类型2导出。
	返回值：
		无
	调用说明：
	exportDataWindowToExcel("dwpersmuster", "0", document.all.corp_name.value);
	exportDataWindowToExcel("dwpersmuster", "4", document.all.corp_name.value);
	exportDataWindowToExcel("dwpersmuster", "1", document.all.corp_name.value);
	exportDataWindowToExcel("dwpersmuster", "2", document.all.corp_name.value);
	exportDataWindowToExcel("dwpersmuster", "1", document.all.corp_name.value, "insr_code,acc_no,idcard");
*/
function exportDataWindowToExcel(dwId, flag, title, txtcols, content) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return -1;
    }

    if (flag === undefined || flag === null) {
        flag = "0";
    }

    if (title === undefined || title === null) {
        title = "";
    }
    if (txtcols === undefined || txtcols === null) {
        txtcols = "";
    }

    var dwSyntax = "";
    var dwData = "";
    if (flag == '3') {
        dwSyntax = dwObj.describe("DataWindow.Syntax");
        if (content === undefined || content === null) {
            dwData = dwObj.describe("DataWindow.Data.HTML");
        } else {
            dwData = content;
        }
    } else {
        if (dwObj.GetFullState() >= 0) {
            dwSyntax = "fullstate";
            dwData = dwObj.GetFullStateBlob();
        } else {
            dwSyntax = dwObj.describe("DataWindow.Syntax");
            if (dwObj.rowcount() > 0) {
                dwData = dwObj.describe("DataWindow.Data");
            }
        }
    }

    var dwDataObject = dwObj.DataWindowObject;
    var flags = flag + "|" + title + "%%%" + txtcols + "|";

    //执行程序名称 版本号 安装程序相对路径 导出标志（|分隔） 数据窗口id 数据窗口语法 数据窗口数据
    internalExportDatawindowToExcel(flags, dwDataObject, dwSyntax, dwData);
}

/*打印数据窗口[可缩放打印]
	dwId：
		数据窗口id
	返回值：
		无
	调用说明：
	printDataWindow("dw_medi_trade_edit");
*/
function printDataWindow(dwId) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return;
    }

    var flag = "p";
    var title = "";
    var txtcols = "";

    var dwSyntax = "";
    var dwData = "";
    if (dwObj.GetFullState() >= 0) {
        dwSyntax = "fullstate";
        dwData = dwObj.GetFullStateBlob();
    } else {
        dwSyntax = dwObj.describe("DataWindow.Syntax");
        if (dwObj.rowcount() > 0) {
            dwData = dwObj.describe("DataWindow.Data");
        }
    }

    var dwDataObject = dwObj.DataWindowObject;
    var flags = flag + "|" + title + "%%%" + txtcols + "|";

    //执行程序名称 版本号 安装程序相对路径 导出标志（|分隔） 数据窗口id 数据窗口语法 数据窗口数据
    internalExportDatawindowToExcel(flags, dwDataObject, dwSyntax, dwData);
}

/*选择打印数据窗口[只支持grid风格的数据窗口]
	dwId：
		数据窗口id
	返回值：
		无
	调用说明：
	printDataWindowSelect("dw_medi_trade_edit");
*/
function printDataWindowSelect(dwId) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return;
    }

    var flag = "s";
    var title = "";
    var txtcols = "";

    var dwSyntax = "";
    var dwData = "";
    if (dwObj.GetFullState() >= 0) {
        dwSyntax = "fullstate";
        dwData = dwObj.GetFullStateBlob();
    } else {
        dwSyntax = dwObj.describe("DataWindow.Syntax");
        if (dwObj.rowcount() > 0) {
            dwData = dwObj.describe("DataWindow.Data");
        }
    }

    var dwDataObject = dwObj.DataWindowObject;
    var flags = flag + "|" + title + "%%%" + txtcols + "|";

    //执行程序名称 版本号 安装程序相对路径 导出标志（|分隔） 数据窗口id 数据窗口语法 数据窗口数据
    internalExportDatawindowToExcel(flags, dwDataObject, dwSyntax, dwData);
}

/*内部导出excel函数*/
function internalExportDatawindowToExcel(flags, dwDataObject, dwSyntax, dwData) {
    var controlObj = null;
    var divObj = null;
    var objName = "_objcontrol";
    var divName = "_objcontent";
    var exefileVer = "";
    try {
        divObj = document.getElementById(divName);
        if (divObj == null) {
            divobj = document.createElement('div');
            divobj.id = divName;
            divobj.style.visibility = "hidden";

            document.body.appendChild(divobj);
        }

        var divhtml = '<object id="' + objName + '" style="VISIBILITY: hidden; display: none;" codeBase="HygeiaWebControl.ocx#version=1,0,0,1" classid="clsid:3B8879AF-211F-46F3-AC41-041793C5060B"></object>';
        document.getElementById(divName).innerHTML = divhtml;

        controlObj = document.getElementById(objName);
        if (controlObj != null) {
            exefileVer = controlObj.GetFileVersion(_dwToolExe);
        }
    } catch(e) {
        setupTools();
        //alert(_dwToolName + "安装失败。" + "\r\n错误号：" + e.number + "\r\n错误信息:" + e.message);
        return false;
    }

    if (controlObj == null) {
        document.getElementById(divName).innerHTML = "";
        alert(_dwToolName + "加载失败。");
        return false;
    }

    try {
        if (upgradeTools(exefileVer)) {
            return false;
        }
    } catch(e) {
        alert(_dwToolName + "升级出错。\r\n错误号：" + e.number + "\r\n错误信息:" + e.message);
        return false;
    }

    try {
        controlObj.ExportDataWindowToExcel(_dwToolExe, flags, dwDataObject, dwSyntax, dwData);
        return true;
    } catch(e) {
        alert(_dwToolName + "运行出错。\r\n错误号：" + e.number + "\r\n错误信息:" + e.message);
        return false;
    } finally {
        controlObj = null;
        document.getElementById(divName).innerHTML = "";
    }
}

/*获取安装绝对地址*/
function getSetupUrl() {
    var setupurl = "";
    if (window.location.protocol.toLowerCase().indexOf("http") >= 0) {
        var href = window.location.href;
        var arr = href.split("/");
        if (arr.length > 4) {
            var pos = href.indexOf("/" + arr[4]);
            if (pos > 0) {
                setupurl = href.substring(0, pos) + "/resource/setup/";
            }
        }
    }

    return setupurl;
}

/*安装工具程序*/
var hideObjectArray = [];
function setupTools() {
    var setupurl = getSetupUrl() + "setupExportTools12.exe";

    var allSelObj = document.getElementsByTagName("select");
    for (var i = 0; i < allSelObj.length; i++) {
        if (allSelObj[i].getAttribute("hide") != "true") {
            hideObjectArray.push(allSelObj[i]);
            allSelObj[i].style.display = "none";
        }
    }
    var allObj = document.getElementsByTagName("object");
    for (var i = 0; i < allObj.length; i++) {
        if (allObj[i].getAttribute("hide") != "true") {
            hideObjectArray.push(allObj[i]);
            allObj[i].style.display = "none";
        }
    }

    var popUp = document.getElementById("_popupcontent");
    if (popUp == null) {
        popUp = document.createElement('div');
        popUp.id = "_popupcontent";

        popUp.style.position = "absolute";
        popUp.style.visibility = "hidden";
        popUp.style.overflow = "hidden";

        popUp.style.background = "#eeeeee";
        popUp.style.border = "1px solid #aaccee";
        popUp.style.padding = "10px";

        document.body.appendChild(popUp);
    }

    var w = 500,
    h = 350;
    var t = (document.body.clientHeight - h) / 2;
    var l = (document.body.clientWidth - w) / 2;
    if (t <= 0) {
        t = 5;
    }
    if (l <= 0) {
        l = 5;
    }
    popUp.style.top = t + "px";
    popUp.style.left = l + "px";
    popUp.style.width = w + "px";
    popUp.style.height = h + "px";

    var divtip = [];
    divtip.push('<table width="480" cellpadding="3" cellspacing="5" ID="tableSetup">');
    divtip.push('<tr>');
    divtip.push('<td align="left" valign="middle" width="360">');
    divtip.push('<br/><h2 style="COLOR:red; FONT: 14px 宋体">' + _dwToolName + '安装</h2>');
    divtip.push('</td>');
    divtip.push('</tr>');
    divtip.push('<tr>');
    divtip.push('<td width="480" colspan="2">');
    divtip.push('<font style="COLOR:000000; FONT-SIZE: 12px">');
    divtip.push('<b>请尝试执行下列操作：</b><br/>');
    divtip.push('<ul>');
    divtip.push('<li>控件没有安装或者文件已经损坏，请点击<a id="btnSetup" target="_blank" href="' + setupurl + '" onclick="setTimeout(\'hidePopup()\', 500);"><b>下载安装</b></a>。（如果您使用Windows Vista及以上版本的操作系统，请保存安装程序到本地，然后以管理员身份运行安装程序）</li>');
    divtip.push('<li>控件安装后，请检查输入地址栏下方是否看到黄色的字样“此网站需要运行以下加载项...”，在点击运行加载项后，控件才能使用');
    divtip.push('<li>浏览器安全级别太高，请调整到中或者默认级别，或者启用下列选项：');
    divtip.push('<ul>');
    divtip.push('<li>对标记为可安全执行脚本的ActiveX控件执行脚本(选择启用)</li>');
    divtip.push('<li>运行ActiveX控件和插件(选择启用)</li>');
    divtip.push('</ul></li>');
    divtip.push('</ul></font>');
    divtip.push('</td></tr>');
    divtip.push('<tr><td align="center" valign="middle"><button onclick=\"hidePopup();\">关闭</button></td></tr>');
    divtip.push('</table>');

    popUp.innerHTML = divtip.join("");
    popUp.style.visibility = "visible";

    popUp.focus();
}

/*升级工具程序*/
function upgradeTools(clientVer) {
    var verinfo = "";
    if (clientVer == null || clientVer.length == 0) {
        verinfo = "没有安装";
    } else {
        if (compareSetupVersion(clientVer, _dwToolVer) < 0) {
            verinfo = clientVer;
        }
    }

    if (verinfo.length > 0) {
        var setupurl = getSetupUrl() + "upgradeExportTools12.exe";
        if (confirm(_dwToolName + "有最新版本，是否现在升级？\r\n客户端版本：" + verinfo + "\r\n可升级版本：" + _dwToolVer)) {
            document.location = setupurl;
            return true;
        } else {
        	//至少升级到最小版本号
        	if(verinfo == "没有安装" || compareSetupVersion(clientVer, _dwRequiredVer) < 0){
        		return true;
        	}
        }
    }

    return false;
}

function compareSetupVersion(a, b) {
    if (a == null || a.length == 0) {
        return -1;
    }
    if (a == b) {
        return 0;
    }

    var saA = a.split(".");
    var saB = b.split(".");

    var alen = saA.length;
    var blen = saB.length;
    var len = (alen > blen ? blen: alen);
    for (var i = 0; i < len; i++) {
        var iA = parseInt(saA[i]);
        var iB = parseInt(saB[i]);
        if (iA < iB) {
            return -1;
        } else if (iA > iB) {
            return 1;
        }
    }

    if (alen == blen == len) {
        return 0;
    }

    if (alen < len) {
        return -1;
    }

    return 1;
}

function hidePopup() {
    var popUp = document.getElementById("_popupcontent");
    if (popUp == null) {
        return;
    }
    popUp.style.visibility = "hidden";

    for (var i = 0; i < hideObjectArray.length; i++) {
        hideObjectArray[i].style.display = "";
    }
    hideObjectArray.length = 0;
}
function sortClicked(dwId, dwEvent) {
	if(dwEvent == null){
		return;
	}
	
	sortDataWindow(dwId, dwEvent.Button, dwEvent.Shift, dwEvent.XPos, dwEvent.YPos, dwEvent.Row, dwEvent.Name);
}
function selectClicked(dwId, dwEvent){
	if(dwEvent == null){
		return;
	}
	
	if (dwEvent.Button != 1 || dwEvent.Row < 1) {
	    return;
	}
	
	var dwObj = document.getElementById(dwId);
	if(dwObj == null){
		return;
	}
	dwObj.SelectRow(0, false);
	dwObj.SelectRow(dwEvent.Row, true);
}
function selectRowFocusChanged(dwId, dwEvent){
	if(dwEvent == null){
		return;
	}
	
	if(dwEvent.CurrentRow < 1){
		return;
	}
	
	var dwObj = document.getElementById(dwId);
	if(dwObj == null){
		return;
	}
	dwObj.SelectRow(0, false);
	dwObj.SelectRow(dwEvent.CurrentRow, true);
}
/*排序数据窗口[移植于PB的uo_dw_sort对象]
dwId：
	数据窗口id
Button, Shift, XPos, YPos, Row, Name：
	见pb的mousedown事件说明
返回值：
	无
调用说明：
针对数据窗口新增一个mousedown事件，数据窗口可绑定列的标题必须是列名+_t
<SCRIPT language="JavaScript" event="MouseDown(Button, Shift, XPos, YPos, Row, Name)" for="dw_medi_trade_edit">
	sortDataWindow("dw_medi_trade_edit", Button, Shift, XPos, YPos, Row, Name);
</SCRIPT>
*/
var _dwSortObject = {};
function sortDataWindow(dwId, Button, Shift, XPos, YPos, Row, Name) {
	if (Button != 1 || Row != 0) {
	    return;
	}
	
	var dwObj = document.getElementById(dwId);
	if (dwObj == null) {
	    alert("无法获取数据窗口对象[" + dwId + "]。");
	    return;
	}
	
	var objsort = _dwSortObject[dwId];
	if (objsort === undefined || objsort == null) {
		try {
	        var obj = new Object();
	        obj.colcount = 0;
	        obj.colcount = dwObj.Describe("datawindow.Column.Count") * 1;
	        obj.colnamearray = new Array();
	        obj.colsortarray = new Array();
	
	        for (var j = 1; j <= obj.colcount; j++) {
	            obj.colnamearray[j] = dwObj.Describe("#" + j + ".name").toLowerCase();
	            obj.colsortarray[j] = "D";
	            obj.sortlist = "";
	        }
	        _dwSortObject[dwId] = obj;
	        
	        objsort = obj;
	    } catch(e) {
	        alert("生成数据窗口[" + dwId + "]排序列失败，请检查。\r\n\r\n错误信息：" + e.message);
	        return;
	    }
	}
	
	var sort = "";
	var len = Name.length;
	if (len > 2 && Name.substring(len - 2, len) == "_t") {
	    var colname = Name.substring(0, len - 2).toLowerCase();
	    for (var i = 1; i <= objsort.colcount; i++) {
	        if (objsort.colnamearray[i] == colname) {
	            var order = objsort.colsortarray[i] == "A" ? "D": "A";
	            sort = "#" + i + " " + order;
	
	            objsort.colsortarray[i] = order;
	            break;
	        }
	    }
	}
	
	if (sort.length > 0) {
	    try {
	    	if(Shift == 1){
	    		var a = (objsort.sortlist || "").split(",");
	    		var colName = sort.substring(0, sort.length - 1);
	    		var b = [];
	    		for(var idx = 0; idx < a.length; idx ++){
	    			var temp = a[idx];
	    			if(temp.length == 0){
	    				continue;
	    			}
	    			if(colName == temp.substring(0, temp.length - 1)){
	    				continue;
	    			}
	    			b.push(temp);
	    		}
	    		b.push(sort);
	    		sort = b.join(",");
	    		objsort.sortlist = sort;
	    	} else {
	    		objsort.sortlist = "";
	    	}
	    	dwObj.SetSort(sort);
	        dwObj.Sort();
	    } catch(e) {
	        alert("排序数据窗口[" + dwId + "]出错，请检查。\r\n\r\n错误信息：" + e.message);
	        return;
	    }
	}
}

/*数据窗口查找对象使用方法[移植于PB的n_cst_find]
	1.在页面头增加onfind脚本
		function onfind()
		{
			var selFind = document.all("SelectFind");
			if (selFind.length > 0)
			{
				findDataWindow("dwpersmuster", selFind.value, document.all("TextFind").value);
			}
		}
	2.增加3个页面对象[select input button]
	<table style="PADDING-BOTTOM: 2px; PADDING-TOP: 2px" cellSpacing="0" cellPadding="0" width="100%" border="0">
		<tr>
			<td>
				<select id="SelectFind"></select>&nbsp;
				<input id="TextFind" type="text" autocomplete="off" onkeydown="if(window.event.keyCode == 13){onfind();window.event.returnValue=false;}">&nbsp;
				<input class="button" id="ButtonFind" onclick="onfind()" type="button" value="查  找" name="button_find" width="80px">
			</td>
		</tr>
	</table>
	3.在页面尾添加绑定脚本
	<script>
		bindColDropDownList("dwpersmuster", "SelectFind");
	</script>
*/

/*绑定数据窗口列到下拉列表
	dwId：
		数据窗口id
	ddlName：
		下拉列表框名称
	返回值：
		无
	调用说明：
		数据窗口可绑定列的标题必须是列名+_t
		1.在页面定义一个select对象
			<select id="SelectFind"></select>
		2.在页面文件末尾(</HTML>)执行绑定
			</HTML>
			<script>
				bindColDropDownList("dw_medi_trade_edit", "SelectFind");
			</script>
*/
function bindColDropDownList(dwId, ddlName) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return;
    }

    var ddlObj = document.getElementById(ddlName);
    if (dwObj == null) {
        alert("无法获取下拉列表对象[" + ddlName + "]。");
        return;
    }

    var colcount = dwObj.Describe("datawindow.Column.Count") * 1;
    var colarray = new Array();
    var idx = 0;
    var colname = "";
    var coldisp = "";
    var colidx = "";
    for (var i = 1; i <= colcount; i++) {
        colidx = "#" + i.toString();
        colname = dwObj.Describe(colidx + ".Name").toLowerCase();
        coldisp = dwObj.Describe(colname + "_t.Text");
        if (coldisp != "!") {
            if (dwObj.Describe(colidx + ".visible") == "1") {

                coldisp = coldisp.replace(/(^\s*)|(\s*$)/g, "");
                coldisp = coldisp.replace(/\'|\"|\t|\r|\n/g, "");

                var obj = new Object();
                obj.col_pos = parseInt(dwObj.Describe(colidx + ".x"));
                obj.col_name = colname;
                obj.col_disp = coldisp;

                colarray[idx] = obj;
                idx++;
            }
        }
    }

    if (colarray.length > 1) {
        colarray.sort(new Function("a", "b", "return a.col_pos - b.col_pos;"));
    }

    ddlObj.options.length = 0;
    for (var i = 0; i < idx; i++) {
        var op = document.createElement("option");
        op.text = colarray[i].col_disp;
        op.value = colarray[i].col_name;

        ddlObj.add(op);
    }
}

/*查找数据窗口指定列的值
	dwId：
		数据窗口id
	colName：
		列名
	findValue：
		查询值
	返回值：
		小于0：出错
		0：没有找到
		大于0：行号
	调用说明：
		findDataWindow("dw_medi_trade_edit", "medi_code", "xy123");
*/
function findDataWindow(dwId, colName, findValue) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return -1;
    }

    if (colName == null || colName.length == 0) {
        alert("请输入需要查询的列名。");
        return -1;
    }
    var rowcount = dwObj.RowCount();
    if (rowcount == 0) {
    	alert("没有符合条件的数据。");
        return 0;
    }

    var findexp = buildDataWindowFindExpre(dwObj, colName, findValue);
    if (findexp.length == 0 || findexp == "!") {
        return -1;
    }

    var rowstart = dwObj.GetSelectedRow(0) + 1;
    var rowend = rowcount;

    if (rowstart < 1 || rowstart > rowend) {
        rowstart = 1;
    }

    var rowfound = dwObj.Find(findexp, rowstart, rowend);
    if (rowfound < 1 || rowfound > rowcount) {
        if (rowstart > 1) {
            rowfound = dwObj.Find(findexp, 1, rowstart - 1);
        }

        if (rowfound < 1 || rowfound > rowcount) {
        	alert("没有符合条件的数据。");
            return 0;
        }
    }

    dwObj.ScrollToRow(rowfound);
    dwObj.SelectRow(0, false);
    dwObj.SelectRow(rowfound, true);
    dwObj.SetColumn(colName);
    dwObj.SelectText(1, 255);

    return rowfound;
}

/*获取数据窗口列类型
	dwObj：
		数据窗口对象
	colName：
		列名
	返回值：
		列类型
	调用说明：
		coltype = getDataWindowColumnType(document.getElementById("dw_medi_trade_edit"), "medi_code");
*/
function getDataWindowColumnType(dwObj, colName) {
    var coltype = dwObj.Describe(colName + ".coltype").toLowerCase();
    if (coltype.length >= 5) {
        coltype = coltype.substring(0, 5);
    }
    if (coltype == "" || coltype == "!") {
        return "";
    }

    var ret = "";
    switch (coltype) {
    case "char(":
        ret = "string";
        break;
    case "date":
        ret = "date";
        break;
    case "datet":
        ret = "datetime";
        break;
    case "time":
    case "times":
        ret = "time";
        break;
    case "decim":
        ret = "decimal";
        break;
    default:
        ret = "number";
        break;
    }

    return ret;
}

/*构造数据窗口查找表达式
	dwObj：
		数据窗口对象
	colName：
		列名
	findValue:
		查找值
	返回值：
		表达式["!"表示出错]
	调用说明：
		findexp = buildDataWindowFindExpre(document.getElementById("dw_medi_trade_edit"), "medi_code", "xy123");
*/
function buildDataWindowFindExpre(dwObj, colName, findValue) {
    if (colName == null || colName.length == 0) {
        return "!";
    }

    var coltype = getDataWindowColumnType(dwObj, colName);
    if (coltype == "") {
        return "!";
    }

    var find = "";
    if (findValue != null) {
        find = findValue;
    }
    if (find.indexOf("\'") >= 0) {
        var re = new RegExp("\'", "ig");
        find = find.replace(re, "~\'");
    }
    find = find.toLowerCase();

    var editstyle = dwObj.Describe(colName + ".Edit.Style").toLowerCase();
    var values = "";
    if (editstyle == "edit") {
        if (dwObj.Describe(colName + ".Edit.CodeTable").toLowerCase() == "yes") {
            values = dwObj.Describe(colName + ".Values");
            if (values != null && values != "" && values != "!") {
                editstyle = "codetable";
            }
        }
    }

    var findexp = "";
    if (editstyle == "dddw" || editstyle == "ddlb" || editstyle == "codetable") {
        findexp = "Pos(Lower(LookUpDisplay(" + colName + ")),'" + find + "') > 0";
    } else {
        if (find.length == 0) {
            findexp = "IsNull(" + colName + ")";
            if(coltype.substring(0, 4) == "char"){
            	findexp += " or " + colName + " = ''";
            }
        } else {
            switch (coltype.substring(0, 4)) {
            case "numb":
            case "long":
            case "inte":
            case "deci":
                try {
                    if (isDecimal(find)) {
                        findexp = colName + " = " + find;
                    } else {
                        alert(colName + "是数字列，请输入数字。");
                        findexp = "!";
                    }
                } catch(e) {
                    findexp = "!";
                }
                break;
            case "date":
                try {
                    if (isDate(find)) {
                        findexp = colName + " = Date('" + as_value + "')";
                    } else {
                        alert(colName + "是日期列，请输入日期[yyyy-MM-dd]。");
                        findexp = "!";
                    }
                } catch(e) {
                    findexp = "!";
                }
                break;
            case "time":
                try {
                    if (isTime(find)) {
                        findexp = colName + " = Time('" + as_value + "')";
                    } else {
                        alert(colName + "是时间列，请输入时间[hh:mm:ss]。");
                        findexp = "!";
                    }
                } catch(e) {
                    findexp = "!";
                }
                break;
            default:
               findexp = "Pos(Lower(" + colName + "), '" + find + "') > 0";
               break;
            }
        }
    }

    return findexp;
}

/*通过数据窗口id获取列名列表
	dwId：
		数据窗口id
	返回值：
		逗号分隔的列名列表[""表示出错]
	调用说明：
		collist = getDataWindowColumns("dw_medi_trade_edit");
*/
function getDataWindowColumns(dwId) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return "";
    }

    var cols = dwObj.Describe("DataWindow.Column.Count") * 1;
    var collist = "";
    for (var i = 1; i <= cols; i++) {
        if (collist.length > 0) {
            collist += ",";
        }
        collist += dwObj.Describe("#" + i + ".name");
    }

    collist = collist.toLowerCase();
    return collist;
}

/*通过文件名和数据窗口对象名获取列名列表
	dwFileName:
		文件名（可以是pbd也可以pbl）
	dwObjectName：
		数据窗口对象名称（PB程序里面数据窗口的名称）
	返回值：
		逗号分隔的列名列表[""表示出错]
	调用说明：
		collist = getDataWindowColumnsByFile("h_general.pbd", "dw_indi_cg_reg");
*/
function getDataWindowColumnsByFile(dwFileName, dwObjectName) {
    if (dwFileName == null || dwFileName.length == 0) {
        alert("请输入数据窗口文件名称。");
        return "";
    }

    if (dwObjectName == null || dwObjectName.length == 0) {
        alert("请输入数据窗口对象名称。");
        return "";
    }

    var divname = "div_" + dwObjectName + "_temp";
    var divobj = document.createElement('div');
    divobj.id = divname;
    divobj.style.visibility = "hidden";
    document.appendChild(divobj);

    if (document.getElementById(divname) == null) {
        alert("生成临时DIV对象失败。");
        return "";
    }

    var dwid = "dw_" + dwObjectName + "_temp";
    var dwheight = 0;
    var dwwidth = 0;

    var dwurl = "";
    if (window.location.protocol.toLowerCase().indexOf("http") >= 0) {
        var arr = window.location.pathname.toLowerCase().split("/");
        var relativePath = "";
        var pos = 0;
        for (var i = 0; i < arr.length; i++) {
            pos++;
            if (arr[i] === "biz") {
                break;
            }
        }
        for (var i = pos; i < arr.length; i++) {
            dwurl += "../";
        }
    }
    dwurl += "resource/";

    var s = '<OBJECT id="' + dwid + '" name="' + dwid + '" codeBase="PSDWC120.DLL" height="' + dwheight + '" width="' + dwwidth + '" classid="CLSID:CCCC1503-CCCC-1000-8000-080009AC61A9">' + '<PARAM NAME="SourceFileName" VALUE="' + dwurl + dwFileName + '">' + '<PARAM NAME="DataWindowObject" VALUE="' + dwObjectName + '">' + '<PARAM NAME="SuppressEvents" VALUE="0">' + '<PARAM NAME="VScrollBar" VALUE="1">' + '<PARAM NAME="HScrollBar" VALUE="1">' + '<PARAM NAME="HSplitScroll" VALUE="0">' + '<PARAM NAME="LiveScroll" VALUE="0">' + '</OBJECT>';
    divobj.innerHTML = s;

    var collist = "";
    if (document.getElementById(dwid) != null) {
        document.all(dwid).reset();
        collist = getDataWindowColumns(dwid);
    } else {
        alert("生成数据窗口失败。\n文件名:" + dwFileName + "\n对象名:" + dwObjectName);
    }

    divobj.innerHTML = "";
    divobj.parentNode.removeChild(divobj);
    divobj = null;

    return collist;
}

/*获取数据窗口
dwId：
	数据窗口id
返回值：
	数据窗口对象(可能为空)
调用说明：
	var dwObj = getDataWindow("dw_medi_trade_edit");
*/
function getDataWindow(dwId){
	return document.getElementById(dwId);
}

/*获取子数据窗口
dwId：
	数据窗口id
childName:
	子数据窗口id
返回值：
	子数据窗口对象(可能为空)
调用说明：
	var dddwObj = getDataWindowChild("dw_report", "dw_header");
*/
function getDataWindowChild(dwId, childName){
	var dw = document.getElementById(dwId);
	if(dw != null){
		if(dw.GetChild(childName) == 1) {
			return dw.GetChildObject();
		}
	}
}

/*格式化数字
value：
	数值（必须是数值型对象)
decimals:
	小数位数
返回值：
	格式化数字字符串
调用说明：
	var str = formatNumber(88, 2);
*/
function formatNumber(value, decimals) {
    if (value === undefined || value === null) {
        return "";
    }
    if (decimals === undefined || decimals === null || decimals < 1) {
        return Math.round(value).toString();
    }

    var a_int = parseInt(value * Math.pow(10, (decimals + 1)));
    if (a_int == 0) {
        var str = "0.";
        for (var i = 0; i < decimals; i++) {
            str += "0";
        }
        return str;
    }

    var a_str = a_int.toString();

    var b_str = a_str.substring(a_str.length - 1, a_str.length);
    if (parseInt(b_str) >= 5) {
        if (value > 0) {
            a_int += 10;
        } else {
            a_int -= 10;
        }
    }

    a_str = a_int.toString();
    var leftlength = a_str.length - (decimals + 1);
    var rightlength = (decimals + 1);
    var leftstr = a_str.substring(0, leftlength);
    var rightstr = a_str.substring(a_str.length - rightlength, a_str.length);
    rightstr = rightstr.substring(0, decimals);
    var c_str = leftstr + "." + rightstr;

    if (value < 1 && value > -1) {
        if (value > 0) {
            c_str = "0." + rightstr;
        } else {
            c_str = "-0." + rightstr;
        }
    }

    return c_str;
}

/*金额小写转换大写
value：
	数值（可以是数值型对象，也可以是字符串大小)
返回值：
	金额大写字符串
调用说明：
	var str = money2cap("12,345,678");
	var str = money2cap(-98765.43);
*/
function money2cap(value) {
    //特例：Null 返回 ""
    if (value === undefined || value === null) {
        return "";
    }

    var ls_num = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
    var ls_unit = [];
    ls_unit[0] = ["元", "万", "亿", "万"];
    ls_unit[1] = ["拾", "拾", "拾", "拾"];
    ls_unit[2] = ["佰", "佰", "佰", "佰"];
    ls_unit[3] = ["仟", "仟", "仟", "仟"];

    var ls_capital_num = "", ls_integer = "", ls_decimal = "", ls_input_num = "";
    var li_integer, li_jiao = 0, li_fen = 0, li_i = 0, li_x = 0, li_y = 0, li_len = 0, li_num = 0, li_last_num = 0;
    var lb_begin = false;

    var strNum = String(value).replace(/^\s+|\s+$/g, "").replace(/,/g, "");
    if (strNum.length == 0) {
        return "";
    }

    var ld_num = parseFloat(strNum);
    if (ld_num === Number.NaN) {
        alert("不是有效的数字");
        return "ERROR";
    }

    //特例：0.00 返回“零元整”
    if (ld_num == 0) {
        return "零元整";
    }

    //分解整数和小数
    ls_input_num = formatNumber(Math.abs(ld_num), 2);

    ls_integer = ls_input_num.substr(0, ls_input_num.length - 3);
    ls_decimal = ls_input_num.substr(ls_input_num.length - 2);
    li_len = ls_integer.length;

    if (ls_integer.length > 16) {
        alert("整数部分不能大于16位");
        return "ERROR";
    }

    //整数部分处理
    li_integer = parseInt(ls_integer);
    ls_capital_num = "";
    if (li_integer != 0) {
        var ls_capital = [];
        for (li_x = 0; li_x < 4; li_x++) {
            ls_capital[li_x] = [];
            for (li_y = 0; li_y < 4; li_y++) {
                ls_capital[li_x][li_y] = "";
            }
        }

        lb_begin = true;
        li_last_num = 10;
        for (li_i = 0; li_i < li_len; li_i++) {
            li_num = parseInt(ls_integer.substr(li_len - 1 - li_i, 1));
            li_y = Math.floor(li_i / 4);
            li_x = li_i - li_y * 4;

            if (li_num != 0) {
                ls_capital[li_x][li_y] = ls_num[li_num] + ls_unit[li_x][li_y];
                lb_begin = false;
            } else {
                if (li_x == 0) {
                    if (li_y != 0 && li_last_num != 0) {
                        ls_capital[li_x][li_y] = ls_unit[li_x][li_y] + "零";
                    } else {
                        ls_capital[li_x][li_y] = ls_unit[li_x][li_y];
                    }
                } else {
                    if (!lb_begin && li_last_num != 0) {
                        ls_capital[li_x][li_y] = "零";
                    } else {
                        ls_capital[li_x][li_y] = "";
                    }
                }

                //当本段四位数字全为 0 时，不需要本段四位数字的单位
                if (li_x == 3) {
                    if (ls_integer.substr(li_len - 1 - (li_y * 4 + li_x), 4) == "0000" && li_y != 0) {
                        ls_capital[0][li_y] = "";
                    }
                }
            }

            li_last_num = li_num;
        }

        for (li_i = 0; li_i < li_len; li_i++) {
            li_y = Math.floor(li_i / 4);
            li_x = li_i - li_y * 4;
            ls_capital_num = ls_capital[li_x][li_y] + ls_capital_num;
        }
    }

    li_fen = 0;
    var ld_fen = parseFloat(ls_decimal);
    if (ld_fen === Number.NaN) {
        ld_fen = 0;
    }
    //小数部分处理，即添加角分
    if (ld_fen != 0) {
        li_jiao = parseInt(ls_decimal.charAt(0));
        li_fen = parseInt(ls_decimal.charAt(1));
        if (li_jiao > 0) {
            ls_capital_num = ls_capital_num + ls_num[li_jiao] + "角";
        }

        if (li_fen > 0) {
            if (li_jiao == 0 && li_integer > 0) {
                ls_capital_num = ls_capital_num + "零";
            }
            ls_capital_num = ls_capital_num + ls_num[li_fen] + "分";
        }
    }

    //添加“整”
    if (li_fen == 0) {
        ls_capital_num = ls_capital_num + "整";
    }

    //添加“负”
    if (ld_num < 0) {
        ls_capital_num = "负" + ls_capital_num;
    }

    return ls_capital_num;
}

/*导入数据窗口
dwId：
	数据窗口id
data:
	数据对象（必须数组）
resetFlag:
	重置标志（缺省为true)
返回值：
	导入的记录数
调用说明：
	var count = importDataWindowWithArray("dw_2", rows);
	var count = importDataWindowWithArray("dw_2", rows, false);
	//子数据窗口
	var count = importDataWindowWithArray("dw_2|col_1", rows, false);
*/
function importDataWindowWithArray(dwId, data, resetFlag) {
	var dwObj = null;
	if(dwId.indexOf("|") > 0){
		var b = dwId.split("|");
		var dw = document.getElementById(b[0]);
		if (dw == null) {
	        alert("无法获取数据窗口对象[" + b[0] + "]。");
	        return -1;
	    }
		
		if(dw.GetChild(b[1]) == 1) { 
			dwObj = dw.GetChildObject(); 
		} else {
			alert("无法获取子数据窗口对象[" + dwId + "]。");
	        return -1;
		}
	} else {
		dwObj = document.getElementById(dwId);
		
		 if (dwObj == null) {
		     alert("无法获取数据窗口对象[" + dwId + "]。");
		     return -1;
		 }
	}
    
    if(resetFlag !== false){
    	dwObj.Reset();
    }
    
    var rowcount = (data !== undefined && data != null) ? data.length : 0;
    if(rowcount < 1){
    	return 0;
    }
    
    var keys = [];
    for (var property in data[0]){
    	keys.push(property);
    }
	var keycount = keys.length;
	
	var rowsPerDetailCount = 1;
	var rowsPerDetailStr = dwObj.Describe("DataWindow.Rows_Per_Detail");
	if(rowsPerDetailStr != null && rowsPerDetailStr.length > 0 && rowsPerDetailStr != '?' && rowsPerDetailStr != '!'){
		rowsPerDetailCount = parseInt(rowsPerDetailStr);
	}
	
    var colcount = dwObj.Describe("datawindow.Column.Count") * 1;
    var cols = [];
    var col = "", key = "";
    for (var i = 1; i <= colcount; i++) {
    	key = null;
    	col = dwObj.Describe("#" + i + ".Name").toLowerCase();
    	if(rowsPerDetailCount > 1){
    		col = col.substring(0, col.length - 2);
    	}
    	for(var j = 0; j < keycount; j ++){
    		if(col == keys[j].toLowerCase()){
    			key = keys[j];
    			break;
    		}
    	}
        cols.push(key);
    }
    
    var colvalue = null;
    var rows = [];
    for(var i = 0; i < rowcount; i ++){
    	var obj = data[i];
    	var row = [];
    	for(var j = 0; j < colcount; j ++){
    		colvalue = "";
    		key = cols[j];
    		if(key != null){
    			colvalue = obj[key];
	    		if(colvalue !== undefined && colvalue != null){
	    			colvalue = colvalue.toString().replace(/\"/g, "\"\"");
	    		} else {
	    			colvalue = "";
	    		}
    		}
    		
    		row.push("\"" + colvalue + "\"");
    	}
    	
    	rows.push(row.join("\t"));
    	row.length = 0;
    }
    
    var str = rows.join("\n");
    rows.length = 0;
    
    return  dwObj.ImportString(1, str, 0, 0, 0, 0, 0);
}

function getDataWindowForString(dwId, options) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return null;
    }
	
    var defualts = {
    	prefix: "",
    	suffix: "",
    	colSeparator: "\t",
    	rowSeparator: "\r\n",
    	dwCols: null,
    	dwRows: null,
    	checkboxCol: null,
    	headerText: null
    };
    
    options = powersi.extend(defualts, options || {});
    
    if (options.dwCols != null && !powersi.isarray(options.dwCols)) {
        alert("列集合必须是数组对象。");
        return null;
    }
    if (options.dwRows != null && !powersi.isarray(options.dwRows)) {
        alert("行集合必须是数组对象。");
        return null;
    }

    dwObj.AcceptText();
    
    var rows = [];
    if(options.headerText != null && options.headerText.length > 0){
    	rows.push(options.headerText);
    }
    
    var rowCount = dwObj.RowCount();
    if (rowCount == 0) {
        return rows.join(options.rowSeparator);
    }

    var colName = "";
    var colValue = "";
  
    var colNames = [];
    var colTypes = [];

    var colCount = 0;
    var colType = "";

    if (options.dwCols != null) {
        colCount = options.dwCols.length;
        for (var j = 0; j < colCount; j++) {
            colNames[j] = options.dwCols[j].toLowerCase();
            colType = dwObj.Describe(colNames[j] + ".coltype").toLowerCase();
            if (colType.length >= 5) {
                colType = colType.substring(0, 5);
            }
            if (colType == "!") {
                colType = "";
            }
            colTypes[j] = colType;
        }
    } else {
        colCount = dwObj.Describe("DataWindow.Column.Count") * 1;
        for (var j = 0; j < colCount; j++) {
            colNames[j] = dwObj.Describe("#" + (j + 1) + ".name").toLowerCase();
            colType = dwObj.Describe("#" + (j + 1) + ".coltype").toLowerCase();
            if (colType.length >= 5) {
                colType = colType.substring(0, 5);
            }
            if (colType == "!") {
                colType = "";
            }
            colTypes[j] = colType;
        }
    }

    colCount = colNames.length;

    if (colCount == 0) {
        return 0;
    }

   
    var rsRow = 0;
    var dwRow = 0;

    if (options.dwRows != null) {
        for (var i = 0; i < options.dwRows.length; i++) {
            dwRow = options.dwRows[i] * 1;
            if (dwRow < 1 || dwRow > rowCount) {
                continue;
            }

            if(options.checkboxCol != null && dwObj.GetItemString(dwRow, options.checkboxCol, 0, false) != "1"){
            	continue;
            }
            
            rsRow++;
            var row = [];
            for (var j = 0; j < colCount; j++) {
                colName = colNames[j];
                colType = colTypes[j];
                colValue = "";
                if (colType != null && colType.length > 0) {
                    colValue = dwObj.GetItemString(dwRow, colName, 0, false);
                } // end cols
                row.push(options.prefix + colValue + options.suffix);
            } //end cols
            
            rows.push(row.join(options.colSeparator));
            row.length = 0;
        } //end rows
    } else {
        for (var i = 1; i <= rowCount; i++) {
        	dwRow = i;
            if(options.checkboxCol != null && dwObj.GetItemString(dwRow, options.checkboxCol, 0, false) != "1"){
            	continue;
            }
            
            rsRow++;
            
            var row = [];
            for (var j = 0; j < colCount; j++) {
                colName = colNames[j];
                colType = colTypes[j];
                colValue = "";
                if (colType != null && colType.length > 0) {
                    colValue = dwObj.GetItemString(dwRow, colName, 0, false);
                } // end colType
                row.push(options.prefix + colValue + options.suffix);
            } //end cols
            rows.push(row.join(options.colSeparator));
            row.length = 0;
        } //end rows
    }

    var str = rows.join(options.rowSeparator);
    rows.length = 0;
    return str;
}

function getDataWindowForArray(dwId, options) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return null;
    }
	
    var defualts = {
    	dwCols: null,
    	dwRows: null,
    	checkboxCol: null
    };
    
    options = powersi.extend(defualts, options || {});
    
    if (options.dwCols != null && !powersi.isarray(options.dwCols)) {
        alert("列集合必须是数组对象。");
        return null;
    }
    if (options.dwRows != null && !powersi.isarray(options.dwRows)) {
        alert("行集合必须是数组对象。");
        return null;
    }

    dwObj.AcceptText();
    
    var rows = [];
    
    var rowCount = dwObj.RowCount();
    if (rowCount == 0) {
        return rows;
    }

    var colName = "";
    var colValue = "";
  
    var colNames = [];
    var colTypes = [];

    var colCount = 0;
    var colType = "";

    if (options.dwCols != null) {
        colCount = options.dwCols.length;
        for (var j = 0; j < colCount; j++) {
            colNames[j] = options.dwCols[j].toLowerCase();
            colType = dwObj.Describe(colNames[j] + ".coltype").toLowerCase();
            if (colType.length >= 5) {
                colType = colType.substring(0, 5);
            }
            if (colType == "!") {
                colType = "";
            }
            colTypes[j] = colType;
        }
    } else {
        colCount = dwObj.Describe("DataWindow.Column.Count") * 1;
        for (var j = 0; j < colCount; j++) {
            colNames[j] = dwObj.Describe("#" + (j + 1) + ".name").toLowerCase();
            colType = dwObj.Describe("#" + (j + 1) + ".coltype").toLowerCase();
            if (colType.length >= 5) {
                colType = colType.substring(0, 5);
            }
            if (colType == "!") {
                colType = "";
            }
            colTypes[j] = colType;
        }
    }

    colCount = colNames.length;

    if (colCount == 0) {
        return 0;
    }

   
    var rsRow = 0;
    var dwRow = 0;

    if (options.dwRows != null) {
        for (var i = 0; i < options.dwRows.length; i++) {
            dwRow = options.dwRows[i] * 1;
            if (dwRow < 1 || dwRow > rowCount) {
                continue;
            }

            if(options.checkboxCol != null && dwObj.GetItemString(dwRow, options.checkboxCol, 0, false) != "1"){
            	continue;
            }
            
            rsRow++;
            var row = {};
            for (var j = 0; j < colCount; j++) {
                colName = colNames[j];
                colType = colTypes[j];
                colValue = "";
                if (colType != null && colType.length > 0) {
                    colValue = dwObj.GetItemString(dwRow, colName, 0, false);
                } // end cols
                row[colName] = colValue;
            } //end cols
            
            rows.push(row);
        } //end rows
    } else {
        for (var i = 1; i <= rowCount; i++) {
        	dwRow = i;
            if(options.checkboxCol != null && dwObj.GetItemString(dwRow, options.checkboxCol, 0, false) != "1"){
            	continue;
            }
            
            rsRow++;
            
            var row = {};
            for (var j = 0; j < colCount; j++) {
                colName = colNames[j];
                colType = colTypes[j];
                colValue = "";
                if (colType != null && colType.length > 0) {
                    colValue = dwObj.GetItemString(dwRow, colName, 0, false);
                } // end colType
                row[colName] = colValue;
            } //end cols
            rows.push(row);
        } //end rows
    }

    return rows;
}

function deleteDataWindow(dwId, options) {
    var dwObj = document.getElementById(dwId);
    if (dwObj == null) {
        alert("无法获取数据窗口对象[" + dwId + "]。");
        return -1;
    }
	
    var defualts = {
    	dwRows: null,
    	checkboxCol: null
    };
    
    options = powersi.extend(defualts, options || {});
    
    if (options.dwRows != null && !powersi.isarray(options.dwRows)) {
        alert("行集合必须是数组对象。");
        return -1;
    }

    var rowCount = dwObj.RowCount();
    if (rowCount == 0) {
        return 0;
    }
    
    if(options.dwRows == null && options.checkboxCol == null){
    	dwObj.Reset();
    	return rowCount;
    }

    var rsRow = 0;
    var dwRow = 0;

    if (options.dwRows != null) {
    	options.dwRows.sort();
        for (var i = (options.dwRows.length - 1); i >= 0; i --) {
            dwRow = options.dwRows[i] * 1;
            if (dwRow < 1 || dwRow > rowCount) {
                continue;
            }

            if(options.checkboxCol != null && dwObj.GetItemString(dwRow, options.checkboxCol, 0, false) != "1"){
            	continue;
            }
            
            rsRow++;
            dwObj.DeleteRow(dwRow);
        } //end rows
    } else {
        for (var i = rowCount; i > 0; i--) {
        	dwRow = i;
            if(options.checkboxCol != null && dwObj.GetItemString(dwRow, options.checkboxCol, 0, false) != "1"){
            	continue;
            }
            
            rsRow++;
            
            dwObj.DeleteRow(dwRow);
        } //end rows
    }
    
    return rsRow;
}

function selectDataWindow(dwId, chkName, chkValue){
	try{
		var dwObj = document.getElementById(dwId);
	    if (dwObj == null) {
	        alert("无法获取数据窗口对象[" + dwId + "]。");
	        return;
	    }
	    
	    var rowCount = dwObj.RowCount();
	    for(var i = 1; i <= rowCount; i ++){
	    	dwObj.SetItem(i, chkName, chkValue);
	    }
	} catch(e){
		alert(e.message);
	}
}